package lumis.service.pagepersonalization.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import lumis.portal.PortalException;
import lumis.portal.controller.ControllerException;
import lumis.portal.controller.ControllerHtml;
import lumis.portal.presentation.perspective.IPortalMode;
import lumis.portal.presentation.perspective.Perspective;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.service.pagepersonalization.widgetmanipulationaction.WidgetManipulationAction;

/**
 * Personalized Page Controller. Responsible for storing user preferences on
 * personalized pages.
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class PagePersonalizationControllerHtml extends ControllerHtml
{
	private static final String PARAMETER_PORTAL_MODE = "mo";
	
	public PagePersonalizationControllerHtml(HttpServletRequest request, HttpServletResponse response, PageContext pageContext)
			throws ControllerException, PortalException
	{
		super(request, response);
	}

	public void handleRequest() throws Exception
	{
		ITransaction transaction = PortalTransactionFactory.createTransaction();
		try
		{
			transaction.begin();
			String method = request.getParameter("m");
			
			if (method == null || "".equals(method))
			{
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				return;
			}
			String className = "lumis.service.pagepersonalization.widgetmanipulationaction."
					+ method.substring(0, 1).toUpperCase()
					+ method.substring(1) + "Action";

			Class<? extends WidgetManipulationAction> clazz = null;
			try
			{
				clazz = Class.forName(className).asSubclass(WidgetManipulationAction.class);
			}
			catch (ClassNotFoundException e)
			{
				response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
				return;
			}
			catch (ClassCastException e)
			{
				response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
				return;
			}

			WidgetManipulationAction action;
			try
			{
				action = clazz.newInstance();
			}
			catch (Exception e)
			{
				response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
				return;
			}

			int portalModeCode = Integer.parseInt(request.getParameter(PARAMETER_PORTAL_MODE));
			IPortalMode portalMode = Perspective.getPortalModeFromCode(portalModeCode);
			int actionStatus = action.doAction(request, portalMode, transaction);
			response.setStatus(actionStatus);
			if (actionStatus == HttpServletResponse.SC_OK)
				transaction.commit();
			else
				transaction.rollback();
		}
		catch (Exception e)
		{
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			transaction.rollback();
		}
		finally
		{
			transaction.dispose();
		}
	}
}
